package com.lgs.app.util;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

/**
 * Created by lgs on 2018/4/20.
 */

public class UpdateAppReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int notifyId = 1;
        int progress = intent.getIntExtra("progress", 0);
        String title = intent.getStringExtra("title");

        NotificationManager nm = null;
        if (UpdateAppUtil.showNotification) {
            Notification notification = new NotificationCompat.Builder(context)
                    .setContentTitle("正在下载 " + title)
                    .setSmallIcon(android.R.mipmap.sym_def_app_icon)
                    .setProgress(100, progress, false)
                    .build();

            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify(notifyId, notification);
        }

        if (progress == 100) {
            if (null != nm) {
                nm.cancel(notifyId);
            }

            if (!TextUtils.isEmpty(DownloadAppUtil.downloadUpdateApkFilePath)) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                File apkFile = new File(DownloadAppUtil.downloadUpdateApkFilePath);

                if (UpdateAppUtil.needFitAndroidN && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    Uri contentUri = FileProvider.getUriForFile(context,
                            context.getPackageName() + ".fileprovider", apkFile);

                    i.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {

                    i.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                }
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        }
    }
}
